<template>
	<div class="system-catalog-container standard-container layout-padding layout-pd">
		<div class="review-list-title">
			<div class="title-actions">
				<el-button size="default" type="primary" class="ml10" @click="handleSearch">
					<el-icon>
						<ele-Search />
					</el-icon>
					{{ $t('message.common.search') }}
				</el-button>

				<el-button size="default" type="primary" class="ml10" @click="onOpenGoodsCatalog('add', null)">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					新增分类
				</el-button>

				<!-- <el-input size="default" placeholder="请输入分类名称" style="max-width: 180px" clearable v-model="state.search.catalogName"> </el-input>
				<el-button size="default" type="primary" class="ml10" @click="handleSearch">
					<el-icon>
						<ele-Search />
					</el-icon>
					{{ $t('message.common.search') }}
				</el-button>

				 
				<el-button size="default" type="primary" class="ml10" @click="onOpenGoodsCatalog('add', null)">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					新增分类
				</el-button> -->
			</div>
		</div>

		<!-- :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" -->
		<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%" row-key="id">
			<!-- <el-table-column type="selection" width="55" /> -->
			<el-table-column label="分类名称" prop="catalogName"> </el-table-column>
			<el-table-column prop="style" label="分类样式" show-overflow-tooltip width="200">
				<template #default="scope">
					<el-tooltip placement="right" effect="light">
						<el-image style="width: 80px; height: 80px" :src="STATIC_URL + getStyleImage(scope.row.style)" fit="cover" />
						<template #content>
							<el-image style="width: 300px; height: 400px" :src="STATIC_URL + getStyleImage(scope.row.style)" fit="cover" />
						</template>
					</el-tooltip>
					<el-image :src="scope.row.picUrl" fit="cover" class="image"></el-image>
				</template>
			</el-table-column>
			<!-- <el-table-column label="分类图片" show-overflow-tooltip>
					<template #default="scope">
						<el-image :src="scope.row.picUrl" fit="contain" class="image"></el-image>
					</template>
				</el-table-column> -->
			<el-table-column prop="used" label="前端使用" show-overflow-tooltip width="200">
				<template #default="scope">
					<el-switch
						v-model="scope.row.used"
						:active-value="1"
						:inactive-value="0"
						active-text="启用"
						inactive-text="未启用"
						@change="used($event, scope.row.id)"
					/>
				</template>
			</el-table-column>
			<!-- <el-table-column label="分类权重" show-overflow-tooltip prop="sortOrder"> </el-table-column> -->

			<el-table-column label="操作时间" prop="updateTime"> </el-table-column>

			<el-table-column label="操作人" prop="updateUsername"> </el-table-column>

			<el-table-column label="权重" show-overflow-tooltip>
				<template #default="scope">
					{{ scope.row.sortOrder }}
				</template>
			</el-table-column>

			<el-table-column label="操作" show-overflow-tooltip width="140">
				<template #default="scope">
					<!-- <el-button size="small" text type="primary" @click="onOpenGoodsCatalog('add', scope.row)">新增</el-button> -->
					<el-button size="small" text type="primary" @click="onOpenGoodsCatalog('edit', scope.row)">修改</el-button>
					<el-button size="small" text type="primary" @click="onOpenGoodsCatalog('delete', scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination-container">
			<el-pagination
				:pager-count="10"
				:page-sizes="[10, 20, 30, 50, 100]"
				v-model:current-page="state.tableData.paging.currentPage"
				background
				v-model:page-size="state.tableData.paging.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.paging.totalCount"
			>
			</el-pagination>
		</div>
		<CatalogDialog ref="CatalogDialogRef" @refresh="refresh"></CatalogDialog>

		<RootCatalogDialog ref="RootCatalogDialogRef"></RootCatalogDialog>
	</div>
</template>

<script setup lang="ts" name="ShopGoodsCatalog">
import { ElMessageBox, messageConfig } from 'element-plus';
import { goodCatalogApi } from '/@/api/goods/catalog';
import msg from '/@/utils/messageUtils';
import { onMounted, reactive, ref, defineAsyncComponent, watch } from 'vue';
import { resolveEndTime, resolveStartTime } from '/@/utils/time/utils';
const CatalogDialog = defineAsyncComponent(() => import('/@/views/goods/catalog/dialog.vue'));

const RootCatalogDialog = defineAsyncComponent(() => import('/@/views/goods/catalog/root_catalog.vue'));

const CatalogDialogRef = ref();

const RootCatalogDialogRef = ref();
import { STATIC_URL } from '/@/utils/config';
import messageUtils from '/@/utils/messageUtils';
const FIRST_ONE = 'static/images/shop/category/first_one.png';
const FIRST_TWO = 'static/images/shop/category/first_two.png';
const SECOND_ONE = 'static/images/shop/category/second_one.png';
const THIRD_ONE = 'static/images/shop/category/third_one.png';

const state = reactive({
	tableData: {
		data: [],
		loading: true,
		total: 0,
		paging: {
			currentPage: 1,
			pageSize: 10,
			totalCount: null,
			totalPages: null,
		},
	},
	search: {
		catalogName: '',
		searchDateTime: '',
	},
	choiceIds: [],
});

const handleSelectionGoods = (goodsCatalogs: any) => {
	state.choiceIds = [];
	goodsCatalogs.forEach((u: any) => {
		state.choiceIds.push(u.id);
	});
};

const getStyleImage = (style: string) => {
	if (style === 'first_one') {
		return FIRST_ONE;
	}

	if (style === 'first_two') {
		return FIRST_TWO;
	}

	if (style === 'second_one') {
		return SECOND_ONE;
	}

	if (style === 'third_one') {
		return THIRD_ONE;
	}
};

const used = async (status: any, id: any) => {
	try {
		console.log('status: ', status, ' , id: ', id);
		await goodCatalogApi().used({
			used: status,
			id: id,
		});
		refresh();
	} catch (e) {
		messageUtils().error('设置失败，请稍后重试');
	}
};

const getTableData = async () => {
	state.tableData.loading = true;
	try {
		const { data } = await goodCatalogApi().search({
			title: state.search.catalogName,
			startTime: resolveStartTime(state.search.searchDateTime),
			endTime: resolveEndTime(state.search.searchDateTime),
			offset: (state.tableData.paging.currentPage - 1) * state.tableData.paging.pageSize,
			limit: state.tableData.paging.pageSize,
		});
		state.tableData.data = data.datas;
		state.tableData.paging.currentPage = data.paging.currentPage;
		state.tableData.paging.totalCount = data.paging.totalCount;
		console.log('data: ', data);
	} catch (error) {
		msg().error('请求失败，请重试');
	} finally {
		state.tableData.loading = false;
	}
};

const onOpenRootCatalog = () => {
	RootCatalogDialogRef.value.onOpenDialog();
};

const onOpenGoodsCatalog = (type: string, row: any) => {
	if (type === 'edit') {
		CatalogDialogRef.value.onOpenDialog(type, row.id);
	} else if (type === 'add') {
		if (row) {
			CatalogDialogRef.value.onOpenDialog(type, row.id);
		} else {
			CatalogDialogRef.value.onOpenDialog(type, null);
		}
	} else {
		ElMessageBox.confirm(`此操作将永久删除商品分类：“${row.catalogName}”，是否继续?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(async () => {
				try {
					await goodCatalogApi().deletedById(row.id);
					msg().success('删除成功');
					refresh();
				} catch (error: any) {
					msg().error(error.msg);
				}
			})
			.catch(() => {});
	}

	// CatalogDialogRef.value.onOpenDialog(type, null);
};

const handleSearch = () => {};

const handleBatchDelete = () => {
	if (state.choiceIds.length == 0) {
		msg().warn('请至少选中一个');
		return;
	}
	ElMessageBox.confirm(`此操作将永久删除选中的商品分类，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await goodCatalogApi().deleted({ ids: state.choiceIds });
				msg().success('批量删除成功');
				refresh();
			} catch (error: any) {
				msg().error(error.msg);
			}
		})
		.catch(() => {});
};

watch(
	() => state.tableData.paging.currentPage,
	(newV, oldv) => {
		console.log(`currentPage, newV: ${newV}, oldV : ${oldv}`);
		onHandleCurrentChange(newV);
	}
);

watch(
	() => state.tableData.paging.pageSize,
	(newV, oldv) => {
		console.log(`pageSize, newV: ${newV}, oldV : ${oldv}`);
		onHandleSizeChange(newV);
	}
);

const refresh = () => {
	onHandleCurrentChange(1);
};

const onHandleSizeChange = (val: number) => {
	state.tableData.paging.pageSize = val;
	state.tableData.paging.currentPage = 1;
	getTableData();
};

const onHandleCurrentChange = (val: number) => {
	state.tableData.paging.currentPage = val;
	getTableData();
};
onMounted(() => {
	getTableData();
});
</script>

<style scoped lang="scss">
.image {
	width: 80px;
	height: 80px;
	cursor: pointer;
}

.system-catalog-container {
	.el-table {
		flex: 1;
	}
}
</style>
